﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;

namespace WeiXinServiceCore.Controllers
{

    /// <summary>
    ///<![CDATA[微信]]>
    /// </summary>
    public class WeiXinController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(WeiXinController));

        /// <summary>
        /// 
        /// </summary>
        public IConfiguration Configuration { get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public WeiXinController(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        /// <summary>
        /// <![CDATA[微信接收通知]]>
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> Notify()
        {
            try
            {
                //1、验证签名
                if (Request.Method.ToUpper() == "GET")
                {            //1.1、验证签名
                    if (WeiXin.Sdk.Common.Util.CheckSignature(Request.Query["nonce"],
                                                              Request.Query["timestamp"],
                                                              Request.Query["signature"],
                                                              Configuration.GetSection("WeiXinOAuth")["Token"]))
                    {
                        return Content(Request.Query["echostr"]);
                    }
                    return Content("签名无效！");
                }
                //2、接收微信消息
                using (System.IO.StreamReader streamReader = new System.IO.StreamReader(Request.Body))
                {
                    string strRecieveBody = await streamReader.ReadToEndAsync();
                    //序列化
                    WeiXin.Sdk.Common.Serialization.XmlSerializer xmlSerializer = new WeiXin.Sdk.Common.Serialization.XmlSerializer(typeof(WeiXin.Sdk.Domain.Messages.Message));
                    var recieve = (WeiXin.Sdk.Domain.Messages.Message)xmlSerializer.Deserialize(strRecieveBody);

                    //事件消息
                    if (recieve.MsgType == WeiXin.Sdk.Common.Constants.SystemConstants.MSG_TYPE.EVENT)
                    {
                        return null;
                    }
                    //被动接收消息
                    else
                    {
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("接收微信通知！", ex);
                return null;
            }
        }
    }
}